package com.szsfm.vehiclemanagement.bean;

import org.greenrobot.greendao.converter.PropertyConverter;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhoubigbo on 2017/12/1.
 */

public class MessageConverter implements PropertyConverter<List<Message>, String> {


    @Override
    public List<Message> convertToEntityProperty(String databaseValue) {
        List<Message> msgs = new ArrayList<>();
        if (databaseValue == null) {
            return msgs;
        } else {

            String[] strings = databaseValue.split("&");


            try {
                for (int i = 0; i < strings.length; i++) {
                    JSONObject msgObj = new JSONObject(strings[i]);
                    int msgid = msgObj.getInt("msgId");
                    int type = msgObj.getInt("type");
                    String title = msgObj.getString("title");
                    String message = msgObj.getString("message");
                    String st = msgObj.getString("timestamp");
                    Message msg = new Message();
                    msg.setMsgId(msgid);
                    msg.setType(type);
                    msg.setTitle(title);
                    msg.setMessage(message);
                    msg.setSubTimestamp(st);
                    msgs.add(msg);
                }
                return msgs;
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return msgs;

    }

    @Override
    public String convertToDatabaseValue(List<Message> entityProperty) {

        StringBuilder sb = new StringBuilder();
        for (int i=0;i<entityProperty.size();i++){
            Message msg = entityProperty.get(i);
            try {
                JSONObject object = new JSONObject();
                object.put("msgId",msg.getMsgId());
                object.put("type",msg.getType());
                object.put("title",msg.getTitle());
                object.put("message",msg.getMessage());
                object.put("timestamp",msg.getSubTimestamp());
                String s =object.toString();
                sb.append(s);
                sb.append("&");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return sb.toString();
    }
}
